package com.example.test0520.fragment;

import android.app.AlertDialog;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;

import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;
import androidx.viewpager2.widget.ViewPager2;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.test0520.R;
import com.example.test0520.api.TtitCallback;
import com.example.test0520.databinding.FragmentWeathBinding;
import com.example.test0520.databinding.FutureListBinding;
import com.example.test0520.util.DateUtils;
import com.example.test0520.util.LifeData;
import com.example.test0520.util.LifeGrid;
import com.example.test0520.util.WeatherData;
import com.sothree.slidinguppanel.SlidingUpPanelLayout;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class WeatherFragment extends Fragment {
    private String mWeather;
    private String mCity;
    private String mTp;
    private String mWid;
    private FragmentWeathBinding binding;
    private static String key = "827a80d1658ed0b9055b479f77824e86";
    private WeatherData body;
    private WeatherData.ResultBean.RealtimeBean bean;
    private List<WeatherData.ResultBean.FutureBean> list;
    private static ViewPager2 pager;
    private List<LifeGrid> gridList = new ArrayList<>();

    public WeatherFragment() {
    }

    public TtitCallback network(String url) {
        TtitCallback ttitCallback = new Retrofit.Builder()
                .baseUrl(url)
                .addConverterFactory(GsonConverterFactory.create())
                .build()
                .create(TtitCallback.class);
        return ttitCallback;
    }

    public static WeatherFragment newInstance(String city, ViewPager2 vp) {
        WeatherFragment fragment = new WeatherFragment();
        Bundle args = new Bundle();
        args.putString("city", city);
        fragment.setArguments(args);
        pager = vp;
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mCity = getArguments().getString("city");
        }

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(LayoutInflater.from(inflater.getContext()), R.layout.fragment_weath, container, false);
        //在上拉进行时和完成时禁用viewpage滑动
        binding.slidingLayout.addPanelSlideListener(new SlidingUpPanelLayout.PanelSlideListener() {
            @Override
            public void onPanelSlide(View panel, float slideOffset) {

            }

            @Override
            public void onPanelStateChanged(View panel, SlidingUpPanelLayout.PanelState previousState, SlidingUpPanelLayout.PanelState newState) {
                if (newState == SlidingUpPanelLayout.PanelState.EXPANDED || newState == SlidingUpPanelLayout.PanelState.DRAGGING) {
                    pager.setUserInputEnabled(false);
                } else {
                    pager.setUserInputEnabled(true);
                }
            }
        });
        binding.cityText.setText(mCity);

        initData();
        return binding.getRoot();
    }

    private void initData() {
        network("http://apis.juhe.cn/simpleWeather/")
                .weatherData(mCity, key)
                .enqueue(new Callback<WeatherData>() {
                    @Override
                    public void onResponse(Call<WeatherData> call, Response<WeatherData> response) {
                        body = response.body();
                        bean = body.getResult().getRealtime();
                        list = body.getResult().getFuture();
                        binding.weatherText.setText(bean.getInfo());
                        binding.wenduText.setText(bean.getTemperature() + "℃");
                        String week = DateUtils.getInstance().getWeek(list.get(0).getDate());
                        String day = list.get(0).getDate().substring(8);
                        binding.dateText.setText(week + "/" + day);
                        FutureAdapter adapter = new FutureAdapter();
                        binding.listView.setAdapter(adapter);
                        switch (bean.getWid()) {
                            case "00":
                                binding.gifImg.setBackgroundResource(R.mipmap.ty);
                                break;
                            case "01":
                            case "02":
                            case "18":
                            case "53":
                                binding.gifImg.setBackgroundResource(R.mipmap.duoyun2);
                                break;
                            case "03":
                            case "04":
                            case "05":
                            case "06":
                            case "07":
                            case "08":
                            case "09":
                            case "10":
                            case "11":
                            case "12":
                            case "19":
                            case "21":
                            case "22":
                            case "23":
                            case "24":
                            case "25":
                                binding.gifImg.setBackgroundResource(R.mipmap.yu1);
                                break;
                            case "13":
                            case "14":
                            case "15":
                            case "16":
                            case "17":
                            case "26":
                            case "27":
                            case "28":
                                binding.gifImg.setBackgroundResource(R.mipmap.xiaxue2);
                                break;
                            default:
                        }

                    }

                    @Override
                    public void onFailure(Call<WeatherData> call, Throwable t) {

                    }
                });
        binding.mainLayout.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                showDialog();
                return true;
            }
        });
    }

    private void showDialog(){
        network("http://apis.juhe.cn/simpleWeather/")
                .getLifeInfo(mCity,key)
                .enqueue(new Callback<LifeData>() {
                    @Override
                    public void onResponse(Call<LifeData> call, Response<LifeData> response) {
                        if (response.body() != null){
                            LifeData.ResultBean.LifeBean life = response.body().getResult().getLife();
                            if (gridList.size()==0){
                                LifeGrid[] data = {
                                        new LifeGrid(R.drawable.ic_car,"洗车",life.getXiche().getV()),
                                        new LifeGrid(R.drawable.ic_yusan,"雨伞",life.getDaisan().getV()),
                                        new LifeGrid(R.drawable.ic_yundong,"运动",life.getYundong().getV()),
                                        new LifeGrid(R.drawable.ic_ziwaixian,"紫外线",life.getZiwaixian().getV()),
                                        new LifeGrid(R.drawable.ic_ganmao,"感冒",life.getGanmao().getV()),
                                        new LifeGrid(R.drawable.ic_diaoyu,"钓鱼",life.getDiaoyu().getV()),
                                };
                                gridList.addAll(Arrays.asList(data));
                            }

                            View view = LayoutInflater.from(getActivity()).inflate(R.layout.life_item, null, false);
                            AlertDialog dialog = new AlertDialog.Builder(getActivity())
                                    .setView(view)
                                    .create();
                            dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
                            GridView lifeGrid = view.findViewById(R.id.life_grid_layout);
                            lifeGrid.setAdapter(new GridAdapter());
                            dialog.show();
                        }
                    }

                    @Override
                    public void onFailure(Call<LifeData> call, Throwable t) {

                    }
                });


    }

    //渲染未来五天的天气数据
    class FutureAdapter extends BaseAdapter {

        private FutureListBinding dataBinding;

        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Object getItem(int position) {
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            WeatherData.ResultBean.FutureBean futureBean = list.get(position);
            dataBinding = DataBindingUtil.inflate(LayoutInflater.from(getActivity()), R.layout.future_list, parent, false);

            dataBinding.futureDate.setText(futureBean.getDate());
            String week = DateUtils.getInstance().getWeek(futureBean.getDate());
            dataBinding.weekText.setText(week);
            dataBinding.sectionText.setText(futureBean.getTemperature());
            dataBinding.futureWendu.setText(futureBean.getWeather());
            return dataBinding.getRoot();
        }
    }

    class GridAdapter extends BaseAdapter{

        @Override
        public int getCount() {
            return gridList.size();
        }

        @Override
        public Object getItem(int position) {
            return gridList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View v;
            if (convertView == null){
                v = LayoutInflater.from(getActivity()).inflate(R.layout.life_grid_item,parent,false);
            }else {
                v = convertView;
            }
            ImageView lifeIcon = v.findViewById(R.id.life_icon);
            TextView lifeType = v.findViewById(R.id.life_type);
            TextView lifeContent = v.findViewById(R.id.life_content);

            lifeIcon.setImageResource(gridList.get(position).getIcon());
            lifeType.setText(gridList.get(position).getType());
            lifeContent.setText(gridList.get(position).getContent());
            return v;
        }
    }
}